package dcl.software.filesync.server.transfer;

import java.io.File;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;

import dcl.software.filesync.server.auth.AuthorizationService;
import dcl.software.filesync.server.auth.User;

@Service
public class TransferServiceImpl implements TransferService {
	@Value("${file.base.directory}")
	private String baseDirectory;
	@Resource
	private AuthorizationService authService;
	@Resource
	private FileRepository fileRepository;

	@Override
	public void transferFile(MultipartFile file, String details, String token) {
		User user = authService.getUserFromToken(token);
		File baseFile = new File(baseDirectory + user.getDirectory());
		if (!baseFile.exists())
			baseFile.mkdir();
		String fileLocation = baseFile + "\\" + file.getOriginalFilename();

		Gson gson = new Gson();
		FileUploadItem fromJson = gson.fromJson(details, FileUploadItem.class);
		fromJson.setServerPath(fileLocation);
		String savedFileId = fileRepository.save(fromJson, user);
		fileLocation = baseFile + "\\" + savedFileId + "-" + file.getOriginalFilename();
		fromJson.setServerPath(fileLocation);
		fileRepository.updateFileName(fromJson, savedFileId);
		try {
			// Files.copy(file.getInputStream(), new
			// File(fileLocation).toPath(), StandardCopyOption.COPY_ATTRIBUTES);
			String tmpLocation = "C:\\Users\\DCLStore\\Desktop\\TMP\\" + savedFileId + "-" + file.getOriginalFilename();
			file.transferTo(new File(tmpLocation));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
